package com.qf.agro.service.sys.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.agro.common.CustomException;
import com.qf.agro.common.ResultInfo;
import com.qf.agro.common.SysUserHolder;
import com.qf.agro.mapper.SysUserMapper;
import com.qf.agro.pojo.*;
import com.qf.agro.service.sys.ModelService;
import com.qf.agro.service.sys.SysUserService;
import com.qf.agro.util.JwtUtil;
import com.qf.agro.vo.SysUserVo;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @company：千峰教育
 * @author：zhy
 * @date：2023/2/20
 */
@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ModelService modelService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Page<SysUser> findPage(Integer pageNum, Integer pageSize, String username) {
        //1. 创建查询条件对象
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        //2.设置查询条件
        wrapper.like(StringUtils.isNotEmpty(username), SysUser::getUsername, username);//where name like %#{name}%
        //设置当前登录用户的企业信息
        //设置当前登录用户的企业信息
        wrapper.eq(SysUser::getCompanyId, SysUserHolder.get().getCompanyId());

        wrapper.orderByDesc(SysUser::getId);
        //3 设置分页条件
        Page<SysUser> page = new Page<>(pageNum, pageSize);
        //4 查询
        page = sysUserMapper.selectPage(page, wrapper);
        //5 返回
        return page;
    }

    @Override
    public ResultInfo save(SysUser sysUser) {
        //1.设置用户状态
        sysUser.setState(1);
        //2.设置用户组id
        sysUser.setGroupId(1l);//TODO 此处目前没有用到
        //3.密码加密
        sysUser.setPassword(SecureUtil.md5("qf1234"));
        //4.设置上级领导和排序号
        sysUser.setManagerId(1L);//TODO 此处目前没有用到上下级关系
        sysUser.setOrderNo(1);//TODO 排序号目前也暂未使用
        //5.保存
        sysUserMapper.insert(sysUser);
        //6.返回
        return ResultInfo.success("添加成功");
    }



    @Override
    public SysUser findById(Long id){
        return sysUserMapper.selectById(id);
    }

    @Override
    public void update(SysUser sysUser) {
        //1.更新
        sysUserMapper.updateById(sysUser);
    }

    @Override
    public void delete(Long id) {
        //此处不是真的删除，而是把状态置为不可用
        //1.创建更新特例
        SysUser sysUser = new SysUser();
        sysUser.setState(0);
        //2.创建更新条件
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getId,id);
        //3.更新用户状态
        sysUserMapper.update(sysUser,queryWrapper);
    }


    @Override
    public ResultInfo login(String username, String password) {
        //1.定义条件查询对象
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        //2.设置条件
        wrapper.eq(SysUser::getUsername,username);
        //3.根据用户名查询用户
        List<SysUser> sysUsers = sysUserMapper.selectList(wrapper);
        //4.判断是不是唯一
        if(sysUsers== null || sysUsers.size() == 0){
            return  ResultInfo.error("账号密码错误，请重新输入");
        }
        //5.判断是不是超过一个
        if(sysUsers.size()>1){
            throw new CustomException("系统问题");
        }
        //6.取出唯一的一个
        SysUser sysUser = sysUsers.get(0);
        //7.判断密码
        if(!StringUtils.equals(sysUser.getPassword(), SecureUtil.md5(password))){
            return  ResultInfo.error("账号密码错误，请重新输入");
        }
        //8.签发token
        String token = JwtUtil.createJWT(sysUser.getId().toString(), JSON.toJSONString(sysUser),null);
        //9.登录成功之后，要根据用户id，查询他具备的功能列表，并存入redis中。
        List<SysModule> modules = modelService.findMenuAll(sysUser.getId());
        //System.out.println(sysUser.getRoleList());
        //10.把当前用户的权限列表存入redis
        redisTemplate.opsForValue().set(sysUser.getId().toString(), modules);
        //11.返回
        return ResultInfo.success(token);
    }


    @Override
    public boolean checkUsername(String username) {
        //1.创建查询条件
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        //2.设置条件
        queryWrapper.eq(SysUser::getUsername,username);
        //3.查询
        List<SysUser> sysUsers = sysUserMapper.selectList(queryWrapper);
        //4.返回
        return (sysUsers==null || sysUsers.size()==0) ? false : true;
    }

}
